<template>
  <div style="margin-right: 10px">
    <el-card style="margin-bottom: 16px">
      <div slot="header" style="display: flex; justify-content: space-between">
        <span><i class="el-icon-collection"></i>{{ query.salesGrade ? query.salesGrade : query.proBrandList + " " }}
          销售类目分析-本年{{ dataYear.dataYear }}</span>
        <span>
          <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExportI">导出</el-button>
        </span>
        <!--  一级类目：
          <el-select v-model="firstLevelColumnList" placeholder="一级类目" style="margin-left: 5px" @change="changeView"
            multiple>
            <el-option v-for="dict in dict.type.sys_sale_category" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
          二级类目：
          <el-select v-model="secondLevelColumnList" placeholder="二级类目" style="margin-left: 5px" @change="changeView"
            multiple>
            <el-option v-for="dict in dict.type.sys_product_secondary" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
          -->
        <!-- <span
                      ><i class="el-icon-collection"></i>
                      {{ query.salesGrade? query.salesGrade: query.proBrandList + " " }}年度完成率</span
                    > -->
      </div>
      <tableDataIII :tableDataList="tableDataI" @handleSortChangeI="handleSortChangeI" />
      <pagination v-show="totalI > 0" :limit.sync="pageReqI.thisPageSize" :page.sync="pageReqI.pageNum" :total="totalI"
        @pagination="getselectLevelColumnAnalysis"></pagination>
    </el-card>

    <el-card style="margin-bottom: 16px">
      <div slot="header" style="display: flex; justify-content: space-between">
        <span><i class="el-icon-collection"></i>{{ query.salesGrade ? query.salesGrade : query.proBrandList + " " }}
          销售类目分析-上一年{{ dataYear.lastdataYear }}</span>
        <span>
          <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExportII">导出</el-button>
        </span>
      </div>
      <tableDataIV :tableDataList="tableDataII" />
      <pagination v-show="totalII > 0" :limit.sync="pageReqII.thisPageSize" :page.sync="pageReqII.pageNum"
        :total="totalII" @pagination="getselectLevelColumnAnalysisLastYear"></pagination>
    </el-card>
    <el-card style="margin-bottom: 16px">
      <div slot="header" style="display: flex; justify-content: space-between">
        <span><i class="el-icon-collection"></i>{{ query.salesGrade ? query.salesGrade : query.proBrandList + " " }}
          销售类目综合对比分析</span>
        <span>
          一级类目：
          <el-select v-model="firstLevelColumnList" placeholder="一级类目" style="margin-left: 5px" @change="changeView"
            multiple>
            <el-option v-for="dict in dict.type.sys_sale_category" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
          <!-- 二级类目：
          <el-select v-model="secondLevelColumnList" placeholder="二级类目" style="margin-left: 5px" @change="changeView"
            multiple>
            <el-option v-for="dict in dict.type.sys_product_secondary" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select> -->
        </span>
      </div>
      <el-table :data="tableData" style="width: 100%" border>
        <el-table-column fixed prop="dataDateUnit" label="" width="100" align="center">
        </el-table-column>
        <el-table-column v-for="(month, index) in months" :key="index" :prop="'salesData.' + index" :label="month"
          align="center" :formatter="(row, col, value) => formatPercentage(value, month, row)">
          <!-- <template slot-scope="scope">
            <span v-if="scope.row.dataDateUnit == '同比'">
              {{ scope.row.salesData[index] }}%
            </span>

            <span v-else>
              {{ scope.row.salesData[index] }}
            </span>
          </template> -->
        </el-table-column>
      </el-table>

      <!-- <tableDataV :tableDataList="barLineData" /> -->
    </el-card>

    <el-row :gutter="20">
      <!-- <el-col :span="16" :xs="24">
        <el-table :data="barLineData" style="width: 100%" border :height="350">
          <el-table-column
            prop="year"
            label="年份"
            width="125"
          ></el-table-column>
          <el-table-column prop="salesAmount" label="全品类销售额" width="150">
          </el-table-column>
          <el-table-column
            prop="salesAmountTop"
            label="top10销售额"
            width="150"
          ></el-table-column>
          <el-table-column
            prop="salesAmountTopRatio"
            label="同期比"
            width="100"
          ></el-table-column>
        </el-table>
      </el-col> -->

      <el-col :span="8" :xs="24">
        <el-card style="margin-bottom: 16px">
          <div slot="header">销售额(单位：万) VS 销售件数</div>
          <barLine :echartDataSku="categoryNewCountYoyChart" />
        </el-card>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-card style="margin-bottom: 16px">
          <div slot="header">折扣 VS 退货</div>
          <barLineIV :echartDataSku="operationLevelNewCountYoyChart" />
        </el-card>
      </el-col>
      <el-col :span="8" :xs="24">
        <!-- <tableList :tableDataList="categoryNewCountYoyList"
        /> -->
        <el-card style="margin-bottom: 16px">
          <div slot="header">访客 vs 转化</div>
          <ve-histogram :data="barLineChart" :settings="chartSettingscompleteRate" style="width: 100%; height: 100%"
            :extend="chartExtend"></ve-histogram>
        </el-card>
      </el-col>
    </el-row>

    <!-- <el-card style="margin-bottom: 16px">
      <div slot="header">
        产品上新分析
       
      </div>
      <barLine :echartDataSku="barLineChart" />
      <tableList :tableDataList="barLineData" />
    </el-card>
    <el-card style="margin-bottom: 16px">
      <div slot="header">
        产品品类上新分析
        
      </div>
      <el-row :gutter="20">
        <el-col :span="16" :xs="24"
          ><barLine :echartDataSku="categoryNewCountYoyChart" />
        </el-col>
        <el-col :span="8" :xs="24">
          <tableList :tableDataList="categoryNewCountYoyList"
        /></el-col>
      </el-row>
    </el-card>
    <el-card style="margin-bottom: 16px">
      <div slot="header">
        新品层级分布
        
      </div>
      <el-row :gutter="20">
        <el-col :span="16" :xs="24"
          ><barLine :echartDataSku="operationLevelNewCountYoyChart" />
        </el-col>
        <el-col :span="8" :xs="24">
          
          <el-table
            :data="operationLevelNewCountYoyList"
            style="width: 100%"
            border
            :height="350"
          >
            <el-table-column
              prop="operationLevel"
              label="层级"
              width="125"
            ></el-table-column>
            <el-table-column prop="newQuantity" label="2023年" width="150">
            </el-table-column>
            <el-table-column
              prop="yoyNewQuantity"
              label="2024年"
              width="150"
            ></el-table-column>
            <el-table-column
              prop="newQuantityYoy"
              label="同期比"
              width="100"
            ></el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-card>

    <el-row :gutter="10">
      <el-col :span="12" :xs="24" v-for="(item, i) in xqpjTableData" :key="i">
        <el-card style="margin-bottom: 16px">
          <div slot="header">
            <span
              ><i class="el-icon-collection"></i>
              {{ item.cpbm }}上新品类层级分布</span
            >
          </div>
          <barLine :echartDataSku="item.name" />
        </el-card>
      </el-col>
    </el-row> -->
  </div>
</template>
<script>
import * as echarts from "echarts/lib/echarts.js";
import {
  selectLevelColumnAnalysis,
  selectLevelColumnAnalysisLastYear,
  selectProductSaleRatioTop,
  selectColumnComprehensiveAnalysis,
  selectColumnComprehensiveStatistics,
} from "@/api/productStructure/BiCategoryBasicsDwd";
import LineChart from "./components/LineChart";
import barLine from "./components/barLine";
import barLineIV from "./components/barLineIV";
import tableList from "./components/table";
import tableDataIII from "./components/tableDataIII";
import tableDataIV from "./components/tableDataIV";
import tableDataV from "./components/tableDataV";

export default {
  dicts: ["sys_sale_category", "sys_product_secondary"],
  props: {
    query: {
      type: Object,
      default: () => { },
    },
    dataYear: {
      type: Object,
      default: () => { },
    },
  },
  components: {
    barLine,
    barLineIV,
    LineChart,
    tableList,
    tableDataIII,
    tableDataIV,
    tableDataV,
  },
  data() {
    this.chartExtend = {
      series(v) {
        v.forEach((i) => {
          i.barWidth = 15;
          i.barGap = 0;
        });
        return v;
      },
      xAxis(v) {
        v.forEach((i) => {
          i.show = true;
          i.splitLine = { show: false };
          i.axisTick = { show: true };
          i.axisLine = { show: true };
        });
        return v;
      },
    };
    this.chartSettingscompleteRate = {
      // "0.[00]a",
      yAxisType: ["0.[00]", "0.[00]%"],
      showLine: ["支付转化率"],
      // yAxisName: ["访客数", "转化率"],
      axisSite: {
        right: ["支付转化率"],
      },
    };
    return {
      ParamsII: { isAsc: true, property: "salesAmount" },
      ParamsI: { isAsc: true, property: "salesAmount" },
      queryParamsI: {},
      //本年
      totalI: 0,
      pageReqI: {
        pageNum: 1,
        thisPageSize: 10,
      },
      //上一年
      queryParamsII: {},
      totalII: 0,
      pageReqII: {
        pageNum: 1,
        thisPageSize: 10,
      },
      firstLevelColumnList: ['上衣'],
      secondLevelColumnList: ['短袖T恤'],
      // TOP5TOP5TOP10TOP30TOP50TOP100TOP200TOP300
      topNumber: 10,
      topNumberList: [
        {
          value: 5,
          label: "TOP5",
        },
        {
          value: 10,
          label: "TOP10",
        },
        {
          value: 30,
          label: "TOP30",
        },
        {
          value: 50,
          label: "TOP50",
        },
        {
          value: 100,
          label: "TOP100",
        },
        {
          value: 200,
          label: "TOP200",
        },
        {
          value: 300,
          label: "TOP300",
        },
      ],
      tableDataI: [], // 用于存储转换后的数据
      tableDataII: [], // 用于存储转换后的数据
      tableData: [], // 用于存储转换后的数据
      months: [], // 用于存储所有月份

      operationLevelNewCountYoyChart: {},
      operationLevelNewCountYoyList: [],

      categoryNewCountYoyChart: {},
      categoryNewCountYoyList: [],
      //对比
      barLineChart: {},
      barLineData: [],

      xqpjTableData: [],
    };
  },
  watch: {
    query: {
      handler: function (newnew, oldold) {
        this.getselectLevelColumnAnalysis();
        this.getselectLevelColumnAnalysisLastYear();

        this.getselectColumnComprehensiveAnalysis();
        this.getselectColumnComprehensiveStatistics();
      },
      deep: true,
      immediate: true,
    },
  },
  created() {
    // this.getList();
  },
  methods: {
    // 数值格式化（自动加百分比）
    formatPercentage(value, label, row) {
      // 判断标签是否包含“比”或“率”
      const isPercentage = /比|率/.test(label) || row.dataDateUnit === '同比';

      if (isPercentage) {
        // 如果数值是小数格式（如 0.15 → 15%）
        return value ? `${value}%` : '0%';

        // 如果数值已经是整数格式（如 15 → 15%）
        // return value ? `${value}%` : '0%';
      } else {
        // 非百分比数值直接显示，可添加千分位（如 1500 → 1,500）
        return value?.toLocaleString() ?? '-';
      }
    },
    getselectColumnComprehensiveStatistics() {
      selectColumnComprehensiveStatistics({
        firstLevelColumnList: this.firstLevelColumnList,
        // secondLevelColumnList: this.secondLevelColumnList,
        ...this.query,
      }).then((response) => {
        let result = [];

        response.forEach((item) => {
          Object.keys(item.keywordProperty).forEach((key) => result.push(key));
        });
        let column = Array.from(new Set(result));
        let columns = ["品类"].concat(column);
        console.log(JSON.stringify(columns));
        this.categoryNewCountYoyChart = {
          columns: columns,
          rows: [],
        };
        this.operationLevelNewCountYoyChart = {
          columns: columns,
          rows: [],
        };
        // this.barLineChart = {
        //   columns: columns.slice(0, -1),
        //   rows: [],
        // };
        response.forEach((item) => {
          if (
            item.dataDateUnit == "销售金额" ||
            item.dataDateUnit == "销售件数"
          ) {
            this.categoryNewCountYoyChart.rows.push({
              品类: item.dataDateUnit,
              ...item.keywordProperty,
            });
          }
          if (item.dataDateUnit == "折扣率" || item.dataDateUnit == "退货率") {
            this.operationLevelNewCountYoyChart.rows.push({
              品类: item.dataDateUnit,
              ...item.keywordProperty,
            });
          }
          // if (
          //   item.dataDateUnit == "商品访客数" ||
          //   item.dataDateUnit == "支付转化率"
          // ) {
          //   this.barLineChart.rows.push({
          //     品类: item.dataDateUnit,
          //     ...item.keywordProperty,
          //   });
          // }
        });
      });
    },
    getselectColumnComprehensiveAnalysis() {
      selectColumnComprehensiveAnalysis({
        firstLevelColumnList: this.firstLevelColumnList,
        // secondLevelColumnList: this.secondLevelColumnList,
        ...this.query,
      }).then((response) => {

        this.tableData = []; // 用于存储转换后的数据
        this.months = []; // 用于存储所有月份
        // 提取所有月份
        response.forEach((item) => {
          for (const month in item.keywordProperty) {
            // const element = array[index];
            if (!this.months.includes(month)) {
              this.months.push(month);
            }
          }
        });
        console.log(JSON.stringify(this.months));

        response.forEach((item) => {
          const row = {
            dataDateUnit: item.dataDateUnit,
            salesData: [],
          };
          this.months.forEach((month) => {
            row.salesData.push(item.keywordProperty[month] || 0);
          });
          this.tableData.push(row);
        });


        this.barLineChart = {
          columns: ["品类", "商品访客数", "支付转化率"],
          rows: [],
        };
        response.forEach((item) => {
          if (item.dataDateUnit != '同比') {
            this.barLineChart.rows.push({
              品类: item.dataDateUnit,
              商品访客数: item.keywordProperty["商品访客数"],
              支付转化率: item.keywordProperty["支付转化率"] / 100,
            });
          }

        });
        return;
        this.barLineChart = {
          columns: ["品类", "访客数", "转化率"],
          rows: [],
        };

        response.forEach((item) => {
          if (item.dataYear != "同期比") {
            this.barLineChart.rows.push({
              品类: item.dataYear,
              访客数: item.visitors ? item.visitors : 0,

              转化率: item.visitorsRatio ? item.visitorsRatio : 0,
            });
          }
        });
      });
    },
    getselectProductSaleRatioTop() {
      selectProductSaleRatioTop(this.query).then((response) => {
        this.barLineData = response;
      });
    },
    changeView() {
      this.getselectLevelColumnAnalysis();
      this.getselectLevelColumnAnalysisLastYear();
      this.getselectColumnComprehensiveAnalysis();
      this.getselectColumnComprehensiveStatistics();
    },
    // 打开加载层
    openLoading() {
      this.$modal.loading("正在加载，请稍候！");
    },
    handleSortChangeI(queryParams) {
      // console.log(JSON.stringify(queryParams));
      this.ParamsI = queryParams
      this.getselectLevelColumnAnalysis()
    },
    getselectLevelColumnAnalysis() {
      this.queryParamsI = {
        // firstLevelColumnList: this.firstLevelColumnList,
        // secondLevelColumnList: this.secondLevelColumnList,
        ...this.query,
        ...this.pageReqI,
      };
      this.openLoading();
      selectLevelColumnAnalysis(this.queryParamsI).then((response) => {
        this.$modal.closeLoading();
        this.tableDataI = response.data;
        this.totalI = response.totalCount;
      });
    },
    handleSortChangeII(queryParams) {
      // console.log(JSON.stringify(queryParams));
      this.ParamsII = queryParams
      this.getselectLevelColumnAnalysisLastYear()
    },
    getselectLevelColumnAnalysisLastYear() {
      this.queryParamsII = {
        // firstLevelColumnList: this.firstLevelColumnList,
        // secondLevelColumnList: this.secondLevelColumnList,
        ...this.query,
        ...this.pageReqII,
      };
      selectLevelColumnAnalysisLastYear(this.queryParamsII).then((response) => {
        this.tableDataII = response.data;
        this.totalII = response.totalCount;
      });
    },
    handleExportI() {
      this.download(
        "productStructure/BiCategoryBasicsDwd/selectLevelColumnAnalysisExport",
        {
          ...this.queryParamsI,
        },
        `selectLevelColumnAnalysisExport_${new Date().getTime()}.xlsx`
      );
    },
    handleExportII() {
      this.download(
        "productStructure/BiCategoryBasicsDwd/selectLevelColumnAnalysisLastYearExport",
        {
          ...this.queryParamsII,
        },
        `selectLevelColumnAnalysisLastYearExport_${new Date().getTime()}.xlsx`
      );
    },
    getproductNewCountYoy() {
      productNewCountYoy(this.query).then((response) => {
        this.barLineData = response.categorySaleTendData;

        this.barLineChart = {
          columns: ["品类", "上新数量", "上一年上新数量", "同比"],
          rows: [],
        };

        response.itemNewTimeYoyList.forEach((item) => {
          this.barLineChart.rows.push({
            品类: item.month,
            上新数量: item.newQuantity,
            上一年上新数量: item.yoyNewQuantity,
            同比: item.newQuantityYoy ? item.newQuantityYoy : 0,
          });
        });
      });
    },
    getcategoryNewCountYoy() {
      categoryNewCountYoy(this.query).then((response) => {
        this.categoryNewCountYoyList = response.categorySaleTendData;
        this.categoryNewCountYoyChart = {
          columns: ["品类", "上新数量", "上一年上新数量", "同比"],
          rows: [],
        };

        response.itemNewTimeYoyList.forEach((item) => {
          this.categoryNewCountYoyChart.rows.push({
            品类: item.category,
            上新数量: item.newQuantity,
            上一年上新数量: item.yoyNewQuantity,
            同比: item.newQuantityYoy ? item.newQuantityYoy : 0,
          });
        });
      });
    },
    getoperationLevelNewCountYoy() {
      operationLevelNewCountYoy(this.query).then((response) => {
        this.operationLevelNewCountYoyList = response;
        this.operationLevelNewCountYoyChart = {
          columns: ["品类", "上新数量", "上一年上新数量", "同比"],
          rows: [],
        };

        response.forEach((item) => {
          this.operationLevelNewCountYoyChart.rows.push({
            品类: item.operationLevel,
            上新数量: item.newQuantity,
            上一年上新数量: item.yoyNewQuantity,
            同比: item.newQuantityYoy ? item.newQuantityYoy : 0,
          });
        });
      });
    },
    getselectProTypeList(category) {
      operationLevelNewCountYoy({ category: category, ...this.query }).then(
        (response) => {
          let obj = {
            columns: ["品类", "上新数量", "上一年上新数量", "同比"],
            rows: [],
          };
          response.forEach((item) => {
            obj.rows.push({
              品类: item.operationLevel,
              上新数量: item.newQuantity,
              上一年上新数量: item.yoyNewQuantity,
              同比: item.newQuantityYoy ? item.newQuantityYoy : 0,
            });
          });
          this.xqpjTableData.forEach((item) => {
            if (item.cpbm == category) {
              item.name = obj;
            }
          });
        }
      );
    },
  },
};
</script>
